package com.jzy.gulimall.gateway.exception;

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.jzy.common.exception.BizCodeEnum;
import com.jzy.common.utils.R;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * @author jzy
 * @date 2020/9/24 20:01
 * 自定义 流控降级返回
 */
@Component
public class SentinelGateWayException {

    //网关限流降级回调
    public SentinelGateWayException(){
        GatewayCallbackManager.setBlockHandler((exchange, t) -> {
            R error = R.error(BizCodeEnum.TOO_MANY_REQUEST.getCode(), BizCodeEnum.TOO_MANY_REQUEST.getMessage());
            String jsonStr = JSONUtil.toJsonStr(error);
            return ServerResponse.ok().body(Mono.just(jsonStr), String.class);
        });
    }
}
